package com.bootdo.front.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.bootdo.common.constant.RoleConstant;
import com.bootdo.company.domain.CompanyDO;
import com.bootdo.company.service.CompanyService;
import com.bootdo.front.domain.*;
import com.bootdo.front.service.*;
import com.bootdo.front.vo.Result;
import com.bootdo.front.vo.ResumeDeleteVo;
import com.bootdo.front.vo.ResumeDeliveryVo;
import com.bootdo.front.vo.ResumeVo;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 简历表
 * 
 * @author wjs
 * @email 1992lcg@163.com
 * @date 2020-02-17 21:13:23
 */
 
@Controller
@RequestMapping("/resume")
public class ResumeController {
	@Autowired
	private ResumeService resumeService;

	@Autowired
	private ProjectExperienceService projectExperienceService;

	@Autowired
	private WorkExperienceService workExperienceService;

	@Autowired
	private PostResumeService postResumeService;

	@Autowired
	private EducationService educationService;

	@Autowired
	private UserService userService;
	@Autowired
	private CompanyService companyService;

	@GetMapping()
	@RequiresPermissions("front:resume:resume")
	String Resume(){
		return "front/resume/resume";
	}

	@ResponseBody
	@GetMapping("/list")
	//@RequiresPermissions("front:resume:resume")
	public PageUtils list(@RequestParam Map<String, Object> params){
		Subject subject = SecurityUtils.getSubject();
		UserDO  userDO = (UserDO)subject.getPrincipal();
		Long roleType = userDO.getRoleType();

		// 根据 userId 判断角色
		if(Long.compare(roleType, RoleConstant.ADMIN_ROLE) == 0 ){
			params.put("roleType",RoleConstant.ADMIN_ROLE);
		} else {
            CompanyDO companyDO = companyService.getByUserId(userDO.getUserId());
            if (companyDO == null) {
                PageUtils pageUtils = new PageUtils(new ArrayList<>(), 0);
                return pageUtils;
            }
            params.put("companyId", companyDO.getId());
		}
		Query query = new Query(params);
		List<ResumeDO> resumeList = resumeService.list(query);
		int total = resumeService.count(query);
		PageUtils pageUtils = new PageUtils(resumeList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	@RequiresPermissions("front:resume:add")
	String add(){
		return "front/resume/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("front:resume:edit")
	String edit(@PathVariable("id") Long id,Model model){
        ResumeDO  resume = resumeService.get(id);
        Subject subject = SecurityUtils.getSubject();
        UserDO  userDO = (UserDO)subject.getPrincipal();
//		UserDO  userDO = userService.get(1L);
        if(userDO == null){
            Result.error(-2,"用户未登入");
        }else{
			ResumeDO userinfo = resumeService.getUserinfo(id);
			resume.setName(userinfo.getUserName());
//			resume.setUserName(userinfo.getUserName());
//			resume.setUserAge(userinfo.getBirth());
            resume.setTel(userinfo.getTel());
//            resume.setTel("1111111111111111");
            resume.setAddress(userinfo.getAddress());
            resume.setEmail(userinfo.getEmail());
            resume.setWorkAge(userDO.getWorking()==null?1:userDO.getWorking());
        }



        if(resume != null ){
            int prop = 1;//占比
            List<ProjectExperienceDO> projectExperiences = projectExperienceService.getByResumeId(resume.getId());
            resume.setProjectExperiences(projectExperiences);
            if(projectExperiences!=null && !projectExperiences.isEmpty()){
                prop++;
            }

            List<WorkExperienceDO> workExperiences = workExperienceService.getByResumeId(resume.getId());
            resume.setWorkExperiences(workExperiences);
            if(workExperiences!=null && !workExperiences.isEmpty()){
                prop++;
            }
            List<EducationDO> educations = educationService.getByResumeId(resume.getId());
            resume.setEducations(educations);
            if(educations!= null && !educations.isEmpty()){
                prop++;
            }

            resume.setProportion(prop == 1 ? "0.3" : prop == 2 ? "0.50" : prop == 3 ? "0.80" :"1.0");

        }
		model.addAttribute("resume", resume);
		return "front/resume/edit";
	}


	/**
	 * 保存
	 *//*
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("front:resume:add")
	public R save( ResumeDO resume){
		if(resumeService.save(resume)>0){
			return R.ok();
		}
		return R.error();
	}
	*//**
	 * 修改
	 *//*
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("front:resume:edit")
	public R update( ResumeDO resume){
		resumeService.update(resume);
		return R.ok();
	}
*/
	/**
	 * 删除
	 */
/*	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("front:resume:remove")
	public R remove( Long id){
		if(resumeService.remove(id)>0){
			return R.ok();
		}
		return R.error();
	}*/

	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("front:resume:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		resumeService.batchRemove(ids);
		return R.ok();
	}


	@ResponseBody
	@GetMapping("/getAllByUserId/{userId}")
	public Result getAllByUserId(@PathVariable("userId") Long userId){
//		Subject subject = SecurityUtils.getSubject();
//		UserDO  userDO = (UserDO)subject.getPrincipal();
//		if(userDO == null){
//			Result.error(-2,"用户未登入");
//		}

		// long userid = userDO.getUserId();
		List<ResumeDO> resumes = resumeService.getByUserId(userId);
		if(resumes != null && !resumes.isEmpty()){
			for(ResumeDO resume: resumes){
				int prop = 1;//占比

				List<ProjectExperienceDO> projectExperiences = projectExperienceService.getByResumeId(resume.getId());
				resume.setProjectExperiences(projectExperiences);
				if(projectExperiences!=null && !projectExperiences.isEmpty()){
					prop++;
				}

				List<WorkExperienceDO> workExperiences = workExperienceService.getByResumeId(resume.getId());
				resume.setWorkExperiences(workExperiences);
				if(workExperiences!=null && !workExperiences.isEmpty()){
					prop++;
				}
				List<EducationDO> educations = educationService.getByResumeId(resume.getId());
				resume.setEducations(educations);
				if(educations!=null && !educations.isEmpty()){
					prop++;
				}

				resume.setProportion(prop == 1 ? "0.3" : prop == 2 ? "0.50" : prop == 3 ? "0.80" :"1.0");
			}
		}

		return Result.ok(resumes);
	}

	@ResponseBody
	@GetMapping("/getById/{id}")
	public Result getById(@PathVariable("id") Long id){

		ResumeDO  resume = resumeService.get(id);
		Subject subject = SecurityUtils.getSubject();
		UserDO  userDO = (UserDO)subject.getPrincipal();
//		UserDO  userDO = userService.get(1L);
		if(userDO == null){
			Result.error(-2,"用户未登入");
		}else{
			resume.setUserAge(userDO.getBirth());
			resume.setTel(userDO.getMobile());
			resume.setAddress(userDO.getLiveAddress());
			resume.setEmail(userDO.getEmail());
			resume.setWorkAge(userDO.getWorking()==null?1:userDO.getWorking());
		}



		if(resume != null ){
			int prop = 1;//占比
			List<ProjectExperienceDO> projectExperiences = projectExperienceService.getByResumeId(resume.getId());
			resume.setProjectExperiences(projectExperiences);
			if(projectExperiences!=null && !projectExperiences.isEmpty()){
				prop++;
			}

			List<WorkExperienceDO> workExperiences = workExperienceService.getByResumeId(resume.getId());
			resume.setWorkExperiences(workExperiences);
			if(workExperiences!=null && !workExperiences.isEmpty()){
				prop++;
			}
			List<EducationDO> educations = educationService.getByResumeId(resume.getId());
			resume.setEducations(educations);
			if(educations!= null && !educations.isEmpty()){
				prop++;
			}

			resume.setProportion(prop == 1 ? "0.3" : prop == 2 ? "0.50" : prop == 3 ? "0.80" :"1.0");

		}
		return Result.ok(resume);
	}

	/**
	 * 新增
	 */
	@ResponseBody
	@RequestMapping("/add")
	public Result add(@RequestBody ResumeVo resume) {
		try {
			if (resume == null || resume.getResume() == null) {
				return Result.error("请传入参数");
			}

			resumeService.save(resume.getUserId(), resume.getResume());
		}catch(Exception e){

			return Result.error("不可新增");
		}

		return Result.ok();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Result update(@RequestBody ResumeVo resume){
		if(resume == null || resume.getResume() == null){
			return Result.error("请传入参数");
		}

		resumeService.update(resume.getUserId(),resume.getResume());
		return Result.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	public Result remove(@RequestBody ResumeDeleteVo resume){
		if(resumeService.remove(resume.getId())>0){
			return Result.ok();
		}
		return Result.error();
	}

	/**
	 * 投递
	 */
	@PostMapping( "/delivery")
	@ResponseBody
	public Result delivery(@RequestBody ResumeDeliveryVo resume){

		PostResumeDO postResume =new PostResumeDO();
		postResume.setPostId(resume.getPostId());
		postResume.setResumeId(resume.getResumeId());
		int save = 0;

		try{
			save = postResumeService.save(postResume);
		} catch(Exception e){
			if(e instanceof DuplicateKeyException){
				//唯一索引约束异常
				return Result.error("已经投递");
			}
		}

		return save>0 ?Result.ok():Result.error();
	}


}
